package com.baixun.gascommon;


import com.alibaba.fastjson.JSONObject;
import com.baixun.gascommon.utils.axcvvvvv;
import com.baixun.gasentity.vo.EvsApiLoginVO;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: 上海燃气驾驶舱
 * @description:
 * @author: yesong
 **/
public class test {
//    public static void main(String[] args) {
//
//        boolean loginResult = axcvvvvv.evsLoginCurrent();
//
//        try {
//            // 首先进行登录并获取 sessionId
//           // loginAndGetSessionId();
//            // 然后请求数据
//            fetchDataAndPrint();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
private static final String LOGIN_API = "/api/v2/login";
    private static final String DOMAIN = "https://evsretail.bce.baidu.com";
    //private static final String STATISTICS_API = "/api/v2/statistics/algorithms?point_rank=safety_production";

    private static final String POINTS_API = "/api/v2/points"; // 查询点位列表
    private static final String AREAS_API = "/api/v2/areas"; // 查询区域列表



    // 登录时的用户名和密码
    private static final String USERNAME = "project_admin_1";
    private static final String PASSWORD = "Bx#evs@2024";
    private static final String API_SECRET = "dspz5nGD";
    private static final String VERIFICATION_CODE = "97fz"; // 示例验证码
    private static final String VERIFICATION_TOKEN = "vcToken_VD3w8EYZ"; // 示例验证码 token

    public static void main(String[] args) {
        // 先动态获取token
        String token = evsLoginCurrent();
        if (token != null) {
            // 用获取到的 token 调用 API
            String response = getSafetyProductionStatistics(token);
            if (response != null) {
                System.out.print("API Response: " + response);
            }
        }
    }

    // 登录并获取 SAAS_SESSION token
    public static String evsLoginCurrent() {
        EvsApiLoginVO loginVO = new EvsApiLoginVO();
        loginVO.setPassword(PASSWORD);
        loginVO.setName(USERNAME);
        loginVO.setVerificationCodeToken(VERIFICATION_TOKEN);
        loginVO.setVerificationCode(VERIFICATION_CODE);

        HashMap<String, String> headers = new HashMap<>();
        // 保持 Base64 拼接顺序：用户名 + API_SECRET + 密码
        String base64String = loginVO.getName() + API_SECRET + loginVO.getPassword();
        String encodedAuth = Base64.getEncoder().encodeToString(base64String.getBytes(StandardCharsets.UTF_8));

        // 设置 Authorization 头为 Base64 编码的字符串
        headers.put("Authorization", encodedAuth);

        // 调用登录接口获取 token
        return postWithHeadersForToken(DOMAIN + LOGIN_API, headers, JSONObject.toJSONString(loginVO));
    }

    // 发起 POST 请求并从响应中提取 token
    private static String postWithHeadersForToken(String url, HashMap<String, String> headers, String jsonString) {
        HttpURLConnection connection = null;
        try {
            // 创建 URL 对象
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 设置请求头
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 查找 Set-Cookie 字段中的 token
                Map<String, List<String>> responseHeaders = connection.getHeaderFields();
                for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {
                    if ("Set-Cookie".equalsIgnoreCase(entry.getKey())) {
                        for (String cookie : entry.getValue()) {
                            if (cookie.startsWith("SAAS_SESSION=")) {
                                // 提取 token
                                String token = cookie.split(";")[0].split("=")[1];
                                System.out.println("Token: " + token);
                                return token;
                            }
                        }
                    }
                }
                System.out.println("Token not found.");
                return null;
            } else {
                System.out.println("Request failed with response code: " + responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    // 使用获取到的 token 调用统计接口
    public static String getSafetyProductionStatistics(String token) {
        HttpURLConnection connection = null;
        try {
            // 构建URL
            URL requestUrl = new URL(DOMAIN + AREAS_API);
            connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法为 GET
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 设置请求头，带上动态获取的 token
            connection.setRequestProperty("Cookie", "SAAS_SESSION=" + token);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 返回响应内容
                return response.toString();
            } else {
                System.out.println("Request failed with response code: " + responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
